// ===============================================
// app_tool
//
// Create by will on 2/23/21 7:45 PM
// Copyright Will.All rights reserved.
// ===============================================

import 'dart:io';

import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

import '../core/exception/directory_extension.dart';
import '../core/logger.dart';

class AppTool {
  AppTool._internal();
  static final encrypt.Key _key = encrypt.Key.fromUtf8('Fight for rights');
  static final encrypt.IV _iv = encrypt.IV.fromUtf8('');

  static final encrypt.AES _aes = encrypt.AES(_key);
  static final encrypt.Encrypter _aesEncrypter = encrypt.Encrypter(_aes);

  static List<int> encryptBytes(List<int> data) {
    return _aesEncrypter.encryptBytes(data, iv: _iv).bytes;
  }

  static List<int> decryptBytes(List<int> data) {
    final encrypted = encrypt.Encrypted(Uint8List.fromList(data));
    return _aesEncrypter.decryptBytes(encrypted, iv: _iv);
  }

  static Future<Directory> getAppDocDirectory(
    AppDirectoryType type, {
    bool createIfNotExist = true,
  }) async {
    final parent = await getApplicationDocumentsDirectory();
    var dirName = type.toString();
    dirName = dirName.substring(dirName.indexOf('.') + 1);

    return parent.getChild(
      childName: dirName,
      createIfNotExist: createIfNotExist,
    );
  }

  static Future<Directory> getTempDirectory(
    AppDirectoryType type, {
    bool createIfNotExist = true,
  }) async {
    final parent = await getTemporaryDirectory();
    var dirName = type.toString();
    dirName = dirName.substring(dirName.indexOf('.') + 1);

    return parent.getChild(
      childName: dirName,
      createIfNotExist: createIfNotExist,
    );
  }

  static Future<void> clearTempDirectory([
    List<AppDirectoryType> types = const <AppDirectoryType>[],
  ]) async {
    for (final type in types) {
      final directory = await getTempDirectory(
        type,
        createIfNotExist: false,
      );
      if (!await directory.exists()) {
        continue;
      }
      await directory.delete(recursive: true).catchError((dynamic error) {
        CoreKitLogger().e('清理临时文件时出错，path: ${directory.path}', error);
      });
    }
  }
}

enum AppDirectoryType {
  voiceMessage,
}

void dPrint(dynamic object) {
  if (!kDebugMode) {
    return;
  }

  final dateTime = DateTime.now();
  debugPrint('[$dateTime] $object');
}
